<?php
/**
 * TopAdmin
 * 版权所有 2018-2027 TopAdmin，并保留所有权利。
 * Author: TopAdmin <8355763@qq.com>
 * Date: 2021/2/27
 */
namespace app\admin\controller\system;

use app\admin\model\AuthGroup;
use app\admin\model\AuthDept;
use app\admin\model\AuthRule;
use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\traits\Curd;
use top\helper\SignHelper;
use top\helper\StringHelper;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use util\Tree;

class Auth extends Backend
{
    use Curd;
    public $uid = '';
    public function initialize()
    {
        $this->uid = Session::get('admin.id');
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->modelClass = new Admin();
    }

    // 管理员列表
    public function admin()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $list =  $this->modelClass->alias('u')
                ->where($where)
                ->join('authDept ad','u.dept_id = ad.id') //此处表别名不能加as
                ->join('authGroup ag','u.group_id = ag.id') //此处表别名不能加as
                ->field('ad.title as deptName,u.*')
                ->field('ag.title as groupName,u.*')
                ->order('u.id desc')
                ->page($page, $limit)
                ->select();
            $total  = $list->count();
            $result = array("code" => 0, "count" => $total, "data" => $list);
            return json($result);
        }
        return view();
    }

    // 管理员添加
    public function add()
    {
        if (Request::isPost()) {
            $data = $this->request->post();
            try{
                $this->validate($data, 'Admin');
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }

                $data['password'] = StringHelper::filterWords($data['password']);
                if(!$data['password']){
                    $data['password']='123456';
                }
                $data['password'] = password_hash($data['password'],PASSWORD_BCRYPT, SignHelper::passwordSalt());
            //添加
            $model = new Admin();
            $result = $model->add($data);
            if ($result) {
                $this->success(lang('add success'), url('system.auth/admin'));
            } else {
                $this->error(lang('add fail'));
            }
        }
        $info = '';
        $auth_group = AuthGroup::where('status', 1)->select();
        $auth_dept = AuthDept::where('status', 1)->select();
        $view = [
            'info'  =>$info,
            'authGroup' => $auth_group,
            'authDept' => $auth_dept,
            'title' => lang('add'),
        ];
        View::assign($view);
        return view();

    }

    /**
     * 管理员修改
     */
    public function edit()
    {
        if (Request::isPost()) {
            $data = $this->request->post();
            if(!$data['username']) $this->error(lang('username').lang('cannot null'));
            if(!$data['password']) $this->error(lang('password').lang('cannot null'));
            if(!$data['group_id']) $this->error(lang('adminGroup').lang('cannot null'));
            $admin = Admin::find($data['id']);
            if(password_verify($data['password'],$admin['password'])){
                unset($data['password']);
            }else{
                $data['password'] = $this->request->post('password', '123456', 'top\helper\StringHelper::filterWords');
                $data['password'] = password_hash($data['password'],PASSWORD_BCRYPT, SignHelper::passwordSalt());
            }
            $model = new Admin();
            $model->edit($data);
            if($this->uid==$data['id']){
                session('admin',null);
            }
            $this->success(lang('edit success'), url('system.auth/admin'));

        } else {
            $id = Request::param('id')?Request::param('id'):$this->uid;
            if ($id) {
                $auth_group = AuthGroup::select();
                $auth_dept = AuthDept::select();
                $admin = Admin::find($id)->toArray();
                unset($admin['password']);
                $view = [
                    'info' => $admin,
                    'authGroup' => $auth_group,
                    'authDept' => $auth_dept,
                    'title' => lang('edit'),
                ];
                View::assign($view);
                return view('add');
            }
        }
    }

    /*** 管理员修改个信信息*/
    public function profile()
    {
        if (Request::isPost()) {
            $data = $this->request->post();
            if(!$data['username']) $this->error(lang('username').lang('cannot null'));
            if(!$data['password']) $this->error(lang('password').lang('cannot null'));
            //if(!$data['group_id']) $this->error(lang('adminGroup').lang('cannot null'));
            $admin = Admin::find($data['id']);
            if(password_verify($data['password'],$admin['password'])){
                unset($data['password']);
            }else{
                $data['password'] = $this->request->post('password', '123456', 'top\helper\StringHelper::filterWords');
                $data['password'] = password_hash($data['password'],PASSWORD_BCRYPT, SignHelper::passwordSalt());
            }
            $model = new Admin();
            $model->edit($data);
            if($this->uid==$data['id']){
                session('admin',null);
            }
            $this->success(lang('edit success'), url('system.auth/admin'));

        } else {
            $id = Request::param('id')?Request::param('id'):$this->uid;
            if ($id) {
                $auth_group = AuthGroup::select();
                $admin = Admin::find($id)->toArray();
                unset($admin['password']);
                $view = [
                    'info' => $admin,
                    'authGroup' => $auth_group,
                    'title' => lang('edit'),
                ];
                View::assign($view);
                return view('profile');
            }
        }
    }


}